<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TypedArray视图</title>
</head>
<body>
    <h1>TypedArray视图</h1>

    <script>
        // 基本用法
        const buffer = new ArrayBuffer(16);

        // 创建不同类型的视图
        const int32View = new Int32Array(buffer);
        const float64View = new Float64Array(buffer);
        const uint8View = new Uint8Array(buffer);

        // 直接创建TypedArray
        const int16Array = new Int16Array(6); // 创建12字节的内存
        int16Array[0] = 42;
        console.log(int16Array.buffer.byteLength); // 12

        // TypedArray的构造方式
        // 1. 参数是数组
        const int8Array = new Int8Array([1, 2, 3, 4]);
        console.log(int8Array); // Int8Array [1, 2, 3, 4]

        // 2. 参数是TypedArray
        const int32Array = new Int32Array(int8Array);
        console.log(int32Array); // Int32Array [1, 2, 3, 4]

        // 3. 参数是ArrayBuffer
        const buffer2 = new ArrayBuffer(8);
        const view = new Int16Array(buffer2, 2, 2); // 从第2个字节开始，长度为2

        // 实际应用示例
        // 1. 音频数据处理
        function processAudioData(audioBuffer) {
            const float32Array = new Float32Array(audioBuffer);
            
            // 对音频数据进行处理
            for (let i = 0; i < float32Array.length; i++) {
                float32Array[i] *= 0.5; // 降低音量
            }
            
            return float32Array.buffer;
        }

        // 2. 图像数据处理
        function createImageData(width, height) {
            const pixels = width * height * 4; // RGBA格式
            const uint8Array = new Uint8Array(pixels);
            
            for (let i = 0; i < pixels; i += 4) {
                uint8Array[i] = 255;   // R
                uint8Array[i+1] = 0;   // G
                uint8Array[i+2] = 0;   // B
                uint8Array[i+3] = 255; // A
            }
            
            return uint8Array;
        }

        // 3. 数据转换
        function convertToInt16Array(numbers) {
            const int16Array = new Int16Array(numbers.length);
            numbers.forEach((num, i) => {
                int16Array[i] = Math.max(-32768, Math.min(32767, num));
            });
            return int16Array;
        }
    </script>
</body>
</html> 